"""
懒加载服务管理器
实现按需启动和自动停止各种服务，减少系统资源占用
"""

import time
import threading
import logging
from typing import Dict, Set, Optional, Callable
from flask import current_app

logger = logging.getLogger('lazy_service_manager')

class LazyServiceManager:
    def __init__(self):
        self.active_services: Set[str] = set()
        self.service_timers: Dict[str, threading.Timer] = {}
        self.service_instances: Dict[str, object] = {}
        self.service_start_functions: Dict[str, Callable] = {}
        self.service_stop_functions: Dict[str, Callable] = {}
        self.lock = threading.Lock()
        
        # 注册服务
        self._register_services()
    
    def _register_services(self):
        """注册所有可懒加载的服务"""
        self.service_start_functions.update({
            'system_monitor': self._start_system_monitor,
            'realtime_monitor': self._start_realtime_monitor,
            'docker_service': self._start_docker_service,
            'network_monitor': self._start_network_monitor,
            'websocket_service': self._start_websocket_service
        })
        
        self.service_stop_functions.update({
            'system_monitor': self._stop_system_monitor,
            'realtime_monitor': self._stop_realtime_monitor,
            'docker_service': self._stop_docker_service,
            'network_monitor': self._stop_network_monitor,
            'websocket_service': self._stop_websocket_service
        })
    
    def start_service_on_demand(self, service_name: str, auto_stop_timeout: int = 300) -> bool:
        """按需启动服务，并设置自动停止定时器"""
        with self.lock:
            if service_name not in self.service_start_functions:
                logger.warning(f"未知服务: {service_name}")
                return False
            
            # 如果服务已经运行，重置定时器
            if service_name in self.active_services:
                logger.debug(f"服务 {service_name} 已在运行，重置自动停止定时器")
                self._reset_auto_stop_timer(service_name, auto_stop_timeout)
                return True
            
            # 启动服务
            try:
                logger.info(f"按需启动服务: {service_name}")
                self.service_start_functions[service_name]()
                self.active_services.add(service_name)
                
                # 设置自动停止定时器
                if auto_stop_timeout > 0:
                    self._set_auto_stop_timer(service_name, auto_stop_timeout)
                
                return True
            except Exception as e:
                logger.error(f"启动服务 {service_name} 失败: {str(e)}")
                return False
    
    def stop_service(self, service_name: str) -> bool:
        """手动停止服务"""
        with self.lock:
            return self._stop_service_internal(service_name)
    
    def _stop_service_internal(self, service_name: str) -> bool:
        """内部停止服务方法"""
        if service_name not in self.active_services:
            logger.debug(f"服务 {service_name} 未运行")
            return True
        
        try:
            logger.info(f"停止服务: {service_name}")
            
            # 取消自动停止定时器
            if service_name in self.service_timers:
                self.service_timers[service_name].cancel()
                del self.service_timers[service_name]
            
            # 停止服务
            if service_name in self.service_stop_functions:
                self.service_stop_functions[service_name]()
            
            # 从活跃服务中移除
            self.active_services.discard(service_name)
            
            return True
        except Exception as e:
            logger.error(f"停止服务 {service_name} 失败: {str(e)}")
            return False
    
    def _set_auto_stop_timer(self, service_name: str, timeout: int):
        """设置自动停止定时器"""
        # 先取消现有定时器
        if service_name in self.service_timers:
            self.service_timers[service_name].cancel()
        
        # 设置新定时器
        timer = threading.Timer(timeout, self._auto_stop_service, [service_name])
        timer.daemon = True
        timer.start()
        self.service_timers[service_name] = timer
        
        logger.debug(f"已设置服务 {service_name} 自动停止定时器，{timeout}秒后停止")
    
    def _reset_auto_stop_timer(self, service_name: str, timeout: int):
        """重置自动停止定时器"""
        self._set_auto_stop_timer(service_name, timeout)
    
    def _auto_stop_service(self, service_name: str):
        """自动停止服务回调"""
        logger.info(f"自动停止服务: {service_name}")
        with self.lock:
            self._stop_service_internal(service_name)
    
    def get_active_services(self) -> Set[str]:
        """获取当前活跃的服务列表"""
        return self.active_services.copy()
    
    def is_service_active(self, service_name: str) -> bool:
        """检查服务是否活跃"""
        return service_name in self.active_services
    
    # 系统监控服务
    def _start_system_monitor(self):
        """启动系统监控服务（基础模式）"""
        if 'system_monitor' not in self.service_instances:
            from . import system_monitor
            # 在Flask应用上下文中启动系统监控
            from flask import current_app
            try:
                with current_app.app_context():
                    # 使用现有的初始化函数
                    scheduler = system_monitor.init_system_monitor(current_app)
                    self.service_instances['system_monitor'] = scheduler
            except RuntimeError as e:
                logger.warning(f"系统监控服务启动失败（无Flask上下文）: {e}")
                return
        logger.info("系统监控服务已启动（基础模式）")
    
    def _stop_system_monitor(self):
        """停止系统监控服务"""
        if 'system_monitor' in self.service_instances:
            scheduler = self.service_instances['system_monitor']
            if scheduler and hasattr(scheduler, 'shutdown'):
                scheduler.shutdown(wait=False)
            del self.service_instances['system_monitor']
        logger.info("系统监控服务已停止")
    
    # 实时监控服务
    def _start_realtime_monitor(self):
        """启动实时监控服务（高频模式）"""
        if 'realtime_monitor' not in self.service_instances:
            from . import system_monitor
            # 在Flask应用上下文中启动实时监控
            from flask import current_app
            try:
                with current_app.app_context():
                    # 使用现有的初始化函数
                    scheduler = system_monitor.init_system_monitor(current_app)
                    self.service_instances['realtime_monitor'] = scheduler
            except RuntimeError as e:
                logger.warning(f"实时监控服务启动失败（无Flask上下文）: {e}")
                return
        logger.info("实时监控服务已启动（高频模式）")
    
    def _stop_realtime_monitor(self):
        """停止实时监控服务"""
        if 'realtime_monitor' in self.service_instances:
            scheduler = self.service_instances['realtime_monitor']
            if scheduler and hasattr(scheduler, 'shutdown'):
                scheduler.shutdown(wait=False)
            del self.service_instances['realtime_monitor']
        logger.info("实时监控服务已停止")
    
    # Docker服务
    def _start_docker_service(self):
        """启动Docker服务"""
        if 'docker_service' not in self.service_instances:
            from .lazy_docker_service import LazyDockerService
            docker_service = LazyDockerService()
            self.service_instances['docker_service'] = docker_service
        logger.info("Docker服务已启动")
    
    def _stop_docker_service(self):
        """停止Docker服务"""
        if 'docker_service' in self.service_instances:
            self.service_instances['docker_service'].close_all_connections()
            del self.service_instances['docker_service']
        logger.info("Docker服务已停止")
    
    # 网络监控服务
    def _start_network_monitor(self):
        """启动网络监控服务"""
        logger.info("网络监控服务已启动")
        # TODO: 实现网络监控逻辑
    
    def _stop_network_monitor(self):
        """停止网络监控服务"""
        logger.info("网络监控服务已停止")
        # TODO: 实现停止逻辑
    
    # WebSocket服务
    def _start_websocket_service(self):
        """启动WebSocket服务"""
        if 'websocket_service' not in self.service_instances:
            from flask_socketio import SocketIO
            socketio = SocketIO()
            if current_app:
                socketio.init_app(current_app,
                    async_mode='gevent',
                    cors_allowed_origins="*",
                    ping_timeout=60,
                    ping_interval=30,
                    max_connections=5  # 限制连接数
                )
            self.service_instances['websocket_service'] = socketio
        logger.info("WebSocket服务已启动")
    
    def _stop_websocket_service(self):
        """停止WebSocket服务"""
        if 'websocket_service' in self.service_instances:
            # WebSocket服务通常不需要显式停止
            del self.service_instances['websocket_service']
        logger.info("WebSocket服务已停止")
    
    def get_service_instance(self, service_name: str):
        """获取服务实例"""
        return self.service_instances.get(service_name)
    
    def shutdown_all(self):
        """关闭所有服务"""
        logger.info("关闭所有懒加载服务")
        with self.lock:
            service_names = list(self.active_services)
            for service_name in service_names:
                self._stop_service_internal(service_name)

# 全局单例
service_manager = LazyServiceManager()

def get_service_manager() -> LazyServiceManager:
    """获取服务管理器单例"""
    return service_manager